package cn.mabach.goods.repository;

import cn.mabach.goods.dao.CategoryDao;
import cn.mabach.goods.entity.CategoryEntity;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.mabach.consts.EhCache.*;

@Repository
@Slf4j
public class CategoryRepository {
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private RedisTemplate redisTemplate;


    //    将类目数的数据存进缓存
    @Cacheable(cacheNames = EHCACHE,key = "'categoryTreeCache'")
    public List<Map> getCategoryTreeFromCache(){

        List<Map> list = (List<Map>) redisTemplate.boundHashOps(CATEGORYTREEREDIS).get(CATEGORYTREEREDISKEY);
        if (list==null){
            return findCategoryTree();
        }
        System.out.println("开始缓存——————————————————————————————————————————————————————————————————————————————————————————");
        return list;
    }



    public List<Map> findCategoryTree(){
        QueryWrapper<CategoryEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("is_show","1").orderByAsc("seq");
        List<CategoryEntity> tbCategories = categoryDao.selectList(wrapper);
        List<Map> list = findByPid(tbCategories, 0);
        redisTemplate.boundHashOps(CATEGORYTREEREDIS).put(CATEGORYTREEREDISKEY,list);
        return list;
    }

    public List<Map> findByPid(List<CategoryEntity> tbCategoryList,Integer pid) {
        ArrayList<Map> list = new ArrayList<>();
        for (CategoryEntity category : tbCategoryList) {
            if (pid.equals(category.getParentId())) {
                Map map = new HashMap<>();
                map.put("name", category.getName());
                map.put("url", category.getUrl());
                map.put("menus", findByPid(tbCategoryList, category.getId()));
                list.add(map);
            }
        }
        return list;
    }
}
